package com.ruoyi.common.utils;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

@Slf4j

public class UserIdByRequest {


    public static Long getUserId(HttpServletRequest request) {
        // 获取Authorization头
        String token = request.getHeader("Authorization");

        // 检查Token是否存在或格式是否正确
        if (token == null || !token.startsWith("Bearer ")) {
            log.warn("Token is missing or invalid");
            return null;
        }

        token = token.substring(7); // 去掉 "Bearer " 前缀
        log.info("Token: " + token);

        // 解析Token
        TokenUser tokenUser = JwtUtils.getTokenUser(token);

        // 检查Token用户是否存在
        if (tokenUser == null) {
            log.warn("Invalid token");
            return null;
        }

        // 返回用户ID
        Long userId = Long.valueOf(tokenUser.getId());
        return userId; // 可以根据需要返回其他信息
    }
}
